import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Typography,
  Divider,
  Switch,
  FormControlLabel,
  Autocomplete,
  InputAdornment,
  Avatar,
  IconButton,
  Chip,
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  Person as PersonIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  Lock as LockIcon,
  PhotoCamera as PhotoCameraIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import {
  CreateUserRequest,
  Status,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { userService } from '@/services/userService';
import { PageHeader } from '@/components/common/PageHeader';

// 表单验证模式
const userFormSchema = z.object({
  username: z.string()
    .min(3, '用户名不能少于3个字符')
    .max(50, '用户名不能超过50个字符')
    .regex(/^[a-zA-Z0-9_-]+$/, '用户名只能包含字母、数字、下划线和横线'),
  password: z.string()
    .min(6, '密码不能少于6个字符')
    .max(50, '密码不能超过50个字符'),
  profile: z.object({
    firstName: z.string().min(1, '名字不能为空'),
    lastName: z.string().min(1, '姓氏不能为空'),
    email: z.string().email('请输入有效的邮箱地址'),
    phone: z.string().optional(),
    avatar: z.string().optional(),
  }),
  status: z.enum(['active', 'inactive', 'pending', 'suspended']),
  roles: z.array(z.string()).min(1, '请至少分配一个角色'),
  departments: z.array(z.string()).optional(),
  positions: z.array(z.string()).optional(),
  tenantIds: z.array(z.string()).optional(),
  organizationIds: z.array(z.string()).optional(),
  organizationId: z.string().min(1, '请选择所属组织'),
  security: z.object({
    twoFactorEnabled: z.boolean(),
    loginNotification: z.boolean(),
  }),
  preferences: z.object({
    language: z.string(),
    timezone: z.string(),
    theme: z.enum(['light', 'dark', 'auto']),
    dateFormat: z.string(),
    timeFormat: z.enum(['12h', '24h']),
    notifications: z.object({
      email: z.boolean(),
      sms: z.boolean(),
      push: z.boolean(),
    }),
  }),
});

type UserFormData = z.infer<typeof userFormSchema>;

const UserCreatePage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant } = useAuth();
  const { showToast } = useAppNotifications();

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string>('');

  // 表单控制
  const {
    control,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm<UserFormData>({
    resolver: zodResolver(userFormSchema),
    defaultValues: {
      username: '',
      password: '',
      profile: {
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        avatar: '',
      },
      status: 'active',
      roles: [],
      departments: [],
      positions: [],
      tenantIds: currentTenant ? [currentTenant.id] : [],
      organizationIds: [],
      organizationId: '',
      security: {
        twoFactorEnabled: false,
        loginNotification: true,
      },
      preferences: {
        language: 'zh-CN',
        timezone: 'Asia/Shanghai',
        theme: 'light',
        dateFormat: 'YYYY-MM-DD',
        timeFormat: '24h',
        notifications: {
          email: true,
          sms: false,
          push: true,
        },
      },
    },
  });

  // 监听姓名变化，自动生成用户名
  const firstName = watch('profile.firstName');
  const lastName = watch('profile.lastName');
  React.useEffect(() => {
    if (firstName && lastName) {
      const username = `${lastName}${firstName}`.toLowerCase()
        .replace(/[^a-z0-9]/g, '')
        .substring(0, 20);
      setValue('username', username);
    }
  }, [firstName, lastName, setValue]);

  // 获取组织列表
  const { data: organizationsData } = useQuery({
    queryKey: ['organizations', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/organizations?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取角色列表
  const { data: rolesData } = useQuery({
    queryKey: ['roles', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/roles?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取部门列表
  const { data: departmentsData } = useQuery({
    queryKey: ['departments', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/departments?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取岗位列表
  const { data: positionsData } = useQuery({
    queryKey: ['positions', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/positions?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 创建用户
  const createMutation = useMutation({
    mutationFn: userService.createUser,
    onSuccess: (response) => {
      showToast({
        type: 'success',
        title: '创建成功',
        message: '用户已成功创建',
      });
      queryClient.invalidateQueries(['users']);
      navigate('/users');
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '创建失败',
        message: error.message || '创建用户时发生错误',
      });
    },
  });

  // 提交表单
  const onSubmit = async (data: UserFormData) => {
    if (!hasPermission('user.create')) {
      showToast({
        type: 'error',
        title: '权限不足',
        message: '您没有创建用户的权限',
      });
      return;
    }

    if (!currentTenant) {
      showToast({
        type: 'error',
        title: '操作失败',
        message: '请先选择租户',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const requestData: CreateUserRequest = {
        ...data,
        tenantId: currentTenant.id,
        profile: {
          ...data.profile,
          fullName: `${data.profile.lastName}${data.profile.firstName}`,
        },
      };
      await createMutation.mutateAsync(requestData);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 处理头像上传
  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setAvatarPreview(result);
        setValue('profile.avatar', result);
      };
      reader.readAsDataURL(file);
    }
  };

  // 生成随机密码
  const generatePassword = () => {
    const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%&*';
    let password = '';
    for (let i = 0; i < 12; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setValue('password', password);
  };

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="创建用户"
        description="创建新的系统用户"
        breadcrumbs={[
          { label: '首页', path: '/' },
          { label: '用户管理', path: '/users' },
          { label: '创建用户' },
        ]}
      />

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={3}>
              {/* 基本信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  基本信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              {/* 头像上传 */}
              <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
                <Box sx={{ position: 'relative', display: 'inline-block' }}>
                  <Avatar
                    src={avatarPreview}
                    sx={{ width: 100, height: 100 }}
                  >
                    <PersonIcon sx={{ fontSize: 50 }} />
                  </Avatar>
                  <IconButton
                    color="primary"
                    component="label"
                    sx={{
                      position: 'absolute',
                      bottom: 0,
                      right: 0,
                      backgroundColor: 'background.paper',
                      '&:hover': {
                        backgroundColor: 'action.hover',
                      },
                    }}
                  >
                    <PhotoCameraIcon />
                    <input
                      type="file"
                      hidden
                      accept="image/*"
                      onChange={handleAvatarChange}
                    />
                  </IconButton>
                </Box>
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.lastName"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="姓氏"
                      fullWidth
                      required
                      error={!!errors.profile?.lastName}
                      helperText={errors.profile?.lastName?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.firstName"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="名字"
                      fullWidth
                      required
                      error={!!errors.profile?.firstName}
                      helperText={errors.profile?.firstName?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="username"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户名"
                      fullWidth
                      required
                      error={!!errors.username}
                      helperText={errors.username?.message || '系统登录名，将根据姓名自动生成'}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <PersonIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="password"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="密码"
                      type={showPassword ? 'text' : 'password'}
                      fullWidth
                      required
                      error={!!errors.password}
                      helperText={errors.password?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <LockIcon />
                          </InputAdornment>
                        ),
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton
                              onClick={() => setShowPassword(!showPassword)}
                              edge="end"
                            >
                              {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                            </IconButton>
                            <Button
                              size="small"
                              onClick={generatePassword}
                              sx={{ ml: 1 }}
                            >
                              生成
                            </Button>
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.email"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="邮箱地址"
                      type="email"
                      fullWidth
                      required
                      error={!!errors.profile?.email}
                      helperText={errors.profile?.email?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <EmailIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.phone"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="手机号码"
                      fullWidth
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <PhoneIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="inactive">禁用</MenuItem>
                        <MenuItem value="pending">待审核</MenuItem>
                        <MenuItem value="suspended">暂停</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              {/* 组织角色 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  组织和角色
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="organizationId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth required>
                      <InputLabel>所属组织</InputLabel>
                      <Select
                        {...field}
                        label="所属组织"
                        error={!!errors.organizationId}
                      >
                        {organizationsData?.data?.map((org: any) => (
                          <MenuItem key={org.id} value={org.id}>
                            {org.name}
                          </MenuItem>
                        ))}
                      </Select>
                      {errors.organizationId && (
                        <Typography variant="caption" color="error" sx={{ mt: 1 }}>
                          {errors.organizationId.message}
                        </Typography>
                      )}
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="roles"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={rolesData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={rolesData?.filter((role: any) => field.value.includes(role.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((role: any) => role.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="用户角色"
                          required
                          error={!!errors.roles}
                          helperText={errors.roles?.message}
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="departments"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={departmentsData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={departmentsData?.filter((dept: any) => field.value?.includes(dept.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((dept: any) => dept.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="所属部门"
                          placeholder="选择部门..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="positions"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={positionsData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={positionsData?.filter((pos: any) => field.value?.includes(pos.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((pos: any) => pos.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="担任岗位"
                          placeholder="选择岗位..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              {/* 安全设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  安全设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="security.twoFactorEnabled"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="启用两步验证"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="security.loginNotification"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="登录通知"
                    />
                  )}
                />
              </Grid>

              {/* 操作按钮 */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
                  <Button
                    variant="outlined"
                    startIcon={<CancelIcon />}
                    onClick={() => navigate('/users')}
                    disabled={isSubmitting}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    startIcon={<SaveIcon />}
                    disabled={isSubmitting || !hasPermission('user.create')}
                  >
                    {isSubmitting ? '创建中...' : '创建用户'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default UserCreatePage;